import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { reqLogin, reqGetUserInfo, reqLogout } from "@/api/user/loginUser";

// 异步action
export const loginAsync = createAsyncThunk(
  "login/loginAsync", // '模块名/函数名'（就是action.type)
  async ({ username, password }: { username: string; password: string }) => {
    // 函数中执行异步操作，操作完成指定返回值（就是action.payload）
    const token = await reqLogin(username, password);
    return token;
  }
);

export const getUserInfoAsync = createAsyncThunk(
  "login/getUserInfoAsync",
  async () => {
    const user = await reqGetUserInfo();
    return user;
  }
);

export const logoutAsync = createAsyncThunk("login/logoutAsync", async () => {
  await reqLogout();
});

const loginSlice = createSlice({
  name: "login",
  initialState(): { name: string; avatar: string; token: string } {
    return {
      token: localStorage.getItem("token") || "", // 用户唯一标识
      name: "", // 用户名
      avatar: "", // 头像
    };
  },
  reducers: {},
  extraReducers(builder) {
    // 处理登录成功 -> 存储token
    builder.addCase(loginAsync.fulfilled, (state, action) => {
      // 在redux存储的数据都是内存存储，刷新没了
      const token = action.payload;
      state.token = token;
      localStorage.setItem("token", token); // 持久化存储
    });
    builder.addCase(getUserInfoAsync.fulfilled, (state, action) => {
      state.name = action.payload.name;
      state.avatar = action.payload.avatar;
    });
    builder.addCase(logoutAsync.fulfilled, (state) => {
      state.name = "";
      state.avatar = "";
      state.token = "";
      localStorage.removeItem("token");
    });
  },
});

export default loginSlice.reducer;
